package com.demo.employees.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * 数据库工具类，用于获取连接和关闭连接等
 */
public class DBUtils {

	public static final String DB_PROPERTIES = "db/jdbc.properties";

	/**
	 * 获取数据库连接
	 * 
	 * @return
	 */
	public static Connection getConnection() {
		InputStream inStream = null;
		Connection conn = null;
		try {
			Properties props = new Properties();
			inStream = DBUtils.class.getClassLoader().getResourceAsStream(DB_PROPERTIES);
			props.load(inStream);

			Class.forName(props.getProperty("jdbc.driverClassName"));
			conn = DriverManager.getConnection(
					props.getProperty("jdbc.url"), 
					props.getProperty("jdbc.username"),
					props.getProperty("jdbc.password"));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != inStream) {
				try {
					inStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return conn;
	}

	/**
	 * 关闭ResultSet-Statement-Connection
	 * @param conn
	 * @param ps
	 * @param rs
	 */
	public static void closeConn(Connection conn, Statement ps, ResultSet rs) {
		if (null != rs) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (null != ps) {
			try {
				ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (null != conn) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
